package com.sunny.shop.service;

import com.sunny.shop.bo.GoodsOrderBO;
import com.sunny.shop.bo.IntegralLogBO;
import com.sunny.shop.core.LocalUser;
import com.sunny.shop.dto.GoodsDTO;
import com.sunny.shop.exception.httpe.NotFoundException;
import com.sunny.shop.model.Good;
import com.sunny.shop.model.GoodsOrder;
import com.sunny.shop.model.IntegralLog;
import com.sunny.shop.model.User;
import com.sunny.shop.repository.GoodRepository;
import com.sunny.shop.repository.GoodsOrderRepository;
import com.sunny.shop.repository.UserRepository;
import com.sunny.shop.util.CommonUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class GoodsServiceImpl {
    @Autowired
    private GoodRepository goodRepository;

    @Autowired
    private GoodsOrderRepository goodsOrderRepository;

    @Autowired
    private UserRepository userRepository;

    public List<Good> getGoods(){
        List<Good> all = this.goodRepository.findAll();
        return all;
    }

    /**
     * 积分兑换
     * @param goodsDTO
     * @return
     */
    public String exchangeGoods(GoodsDTO goodsDTO){
        Long uid = LocalUser.getUser().getId();
        Optional<Good> good = this.goodRepository.findById(goodsDTO.getGoodId());
        if(good == null) throw new NotFoundException(40000);
        User user = this.userRepository.findOneById(uid);
        if(user.getIntegral() < good.get().getIntegral()) throw new NotFoundException(50001);

        // 兑换成功，保存订单
        GoodsOrder goodsOrder = new GoodsOrder();
        String orderSn = CommonUtil.createOrderSn();
        GoodsOrderBO orderBO = GoodsOrderBO.builder()
                .uid(uid)
                .orderSn(orderSn)
                .status(0)
                .integral(good.get().getIntegral())
                .goodsName(good.get().getGoodsName())
                .goodsImg(good.get().getId())
                .createTime(new Date())
                .build();
        BeanUtils.copyProperties(goodsDTO, orderBO);
        BeanUtils.copyProperties(orderBO,goodsOrder);
        goodsOrderRepository.save(goodsOrder);
        Integer afterIntegral = user.getIntegral() - good.get().getIntegral();
        IntegralLogBO bo = IntegralLogBO.builder()
                .uid(uid)
                .integral(good.get().getIntegral())
                .beforeIntegral(user.getIntegral())
                .afterIntegral(afterIntegral)
                .type(3).build();
        IntegralLog integralLog = new IntegralLog();
        BeanUtils.copyProperties(bo, integralLog);
        user.setIntegral(afterIntegral);
        this.userRepository.save(user);
        return orderSn;
    }

    public Good getGoodsDetail(Long id){
        return this.goodRepository.findGoodById(id);
    }
}
